package com.doge.walknovel.business.novel

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.doge.walknovel.analysis.*
import com.doge.walknovel.api.model.NovelDetailInfo
import com.doge.walknovel.api.model.CommentInfo
import com.doge.walknovel.core.base.LoadStatus
import com.doge.walknovel.core.base.adapters.toLiveData
import com.doge.walknovel.utils.isNullOrZero

class NovelDetailViewModel constructor(private val repository: NovelDetailRepository) : ViewModel() {
    val createLoading: LiveData<LoadStatus?> = repository.createLoading
    val loading: LiveData<LoadStatus> = repository.loading
    val bookDetail: LiveData<NovelDetailInfo> = repository.bookDetail
    val dataList = repository.dataSource().toLiveData(
        cellId = { it.id },
        requestMore = { repository.requestNovelComments(false) })

    fun requestNovelInfo() = repository.requestNovelInfo()
    fun requestNovelComments() = repository.requestNovelComments(true)
    fun requestSubmitNovelComments(content: String?, score: Int?) {
        if (score != null)  analysisEvent("${novel_rating}_${score}")
        analysisEvent(comment_post)
        repository.requestSubmitNovelComments(content, score)
    }

    fun requestSubmitReplyComments(commentId: Int, content: String?) {
        analysisEvent(comment_post_reply)
        repository.requestSubmitReplyComments(commentId, content)
    }

    fun requestSubmitChapterComments(content: String?) {
        // 第一期先显示整本书的
        analysisEvent(comment_post_chapter)
        repository.requestSubmitNovelComments(content, null)
    }

    fun requestCollectComments(data: CommentInfo?) {
        if (data == null) return
        if (data.likeFlag == 1) repository.requestUnLikeComments(data)
        else repository.requestLikeComments(data)
    }
}


class NovelDetailViewModelFactory(private val requestId: Int, private val refer: String, private val referId: Int?) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        val rId = if (referId.isNullOrZero()) null else referId
        val repository = NovelDetailRepository(requestId, refer, rId)
        if (modelClass.isAssignableFrom(NovelDetailViewModel::class.java)) {
            return NovelDetailViewModel(repository) as T
        }
        //noinspection unchecked
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

